# coding=utf-8
from datetime import timedelta
from flask import Flask, render_template, request, make_response,jsonify
from flask_sqlalchemy import SQLAlchemy
import config
import os
from flask_cors import *
from main.utils import RequestHelper
import json
basedir = os.path.abspath(os.path.dirname(__file__))


def create_app():
    # flask
    app = Flask(__name__)

    # 解决跨域问题
    CORS(app, supports_credentials=True )

    # 配置数据库
    app.config.from_object(config)
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
    app.config['SECRET_KEY'] = os.urandom(24)  # 设置为24位的字符,每次运行服务器都是不同的，所以服务器启动一次上次的session就清除。
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)  # 设置session的保存时间。
    app.config['JSONIFY_MIMETYPE'] = "application/json;charset=utf-8"  # 指定浏览器渲染的文件类型，和解码格式
    # register blueprint
    from .apis import api_blueprint
    app.register_blueprint(api_blueprint)

    return app


def register_api():
    from .apis import api
    from .apis.user_api import ns as user_api
    from .apis.questionnaire_api import ns as questionnaire_api
    from .apis.result_api import ns as result_api

    api.add_namespace(user_api)
    api.add_namespace(questionnaire_api)
    api.add_namespace(result_api)


app = create_app()
db = SQLAlchemy(app)

# register api namespace
register_api()

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF','jpeg'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def _():
    # import json
    key = False
    par = RequestHelper.formToDict(request)
    if 'appid' in par:
        f = open("key.json", encoding='utf-8')
        f = json.load(f)
        try:
            key = f[par['appid']]
        except:
            return jsonify({'isKey': key})
    return jsonify({'isKey': key})


@app.route('/index')
def key():
    par = RequestHelper.formToDict(request)
    if par['key'] == 'true':
        fileObject = open('key.json', 'w')
        fileObject.write(json.dumps({'isKey': True}))
        fileObject.close()
        return jsonify({'回复': '开关开启'})
    if par['key'] == 'false':
        fileObject = open('key.json', 'w')
        fileObject.write(json.dumps({'isKey': False}))
        fileObject.close()
        return jsonify({'回复': '开关关闭'})
    return jsonify({'回复': '未知操作'})


@app.route('/set',methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        par = RequestHelper.formToDict(request)
        print(par)
        f = request.files['photo']
        if f and allowed_file(f.filename):
            new_filename = 'text.jpg'
            print(f.filename)
            f.save(os.path.join(basedir,'static','images', new_filename))
        if par['appid'] and par['select']:
            f = open("key.json", encoding='utf-8')
            t = json.load(f)
            f.close()
            print('et')
            if par['select'] == 'true':
                t[par['appid']] = True
                fileObject = open('key.json', 'w')
                fileObject.write(json.dumps(t))
                fileObject.close()
                return jsonify({'回复': '开关开启'})
            else:
                t[par['appid']] = False
                fileObject = open('key.json', 'w')
                fileObject.write(json.dumps(t))
                fileObject.close()
                return jsonify({'回复': '开关关闭'})


    return render_template('login.html', method=request.method)

@app.route('/image/<string:image_name>')
def show_image(image_name):
    try:
        if request.method == 'GET':
            if image_name is None:
                pass
            else:
                image_data = open((os.path.join(basedir, 'static', 'images/%s' % image_name)), "rb").read()
                response = make_response(image_data)
                response.headers['Content-Type'] = 'image/png'
                return response
        else:
            pass
    except Exception as e:
        print(e)





